package com.yuanfeng.userms.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.userms.ShopYgUserInfoDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.DateUtils;
import com.yuanfeng.commoms.util.ParseMapUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.fx.GoodsVkSetVO;
import com.yuanfeng.commoms.vo.fx.ShareGoodsVO;
import com.yuanfeng.commoms.vo.fx.VKUserInfoVO;
import com.yuanfeng.commoms.vo.fx.VkApplyOrderVO;
import com.yuanfeng.commoms.vo.goods.FXGoodsListVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.userms.dto.UserApplyConfirmDTO;
import com.yuanfeng.userms.entity.UserVkApplyEntity;
import com.yuanfeng.userms.entity.UserVkEntity;
import com.yuanfeng.userms.entity.UserYgInfoEntity;
import com.yuanfeng.userms.feign.BusinessServiceClient;
import com.yuanfeng.userms.feign.GoodsServiceClient;
import com.yuanfeng.userms.mapper.*;
import com.yuanfeng.userms.service.UserVkService;
import com.yuanfeng.userms.vo.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @ClassName UserVkServiceImpl
 * @Description 店铺微客会员表
 * @Author cyp
 * @Date 2023-06-05 11:00:52
 * @Version 1.0
 **/
@Service
public class UserVkServiceImpl extends ServiceImpl<UserVkMapper, UserVkEntity>
        implements UserVkService {
    @Autowired
    private BusinessServiceClient businessServiceClient;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserInviteRecordMapper userInviteRecordMapper;
    @Autowired
    private UserYgInfoMapper userYgInfoMapper;
    @Autowired
    private UserVipMapper userVipMapper;
    @Autowired
    private UserVkSetMapper userVkSetMapper;
    @Autowired
    private UserVkApplyMapper userVkApplyMapper;
    @Autowired
    private GoodsServiceClient goodsServiceClient;

    private static final Logger logger = LoggerFactory.getLogger(UserVkServiceImpl.class);
    @Override
    public VKUserInfoVO queryVKUserInfo(Map<String, String> paraMap) {
        return this.baseMapper.queryVKUserInfo(paraMap);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult shareGoodsRecord(String data) {
        try {
            // 更新商品分享销量
            ResponseResult resultResp = businessServiceClient.updateFxGoodsSaleNum(data);
            if(resultResp.getCode() != 1){
                return resultResp;
            }
            List<ShareGoodsVO> shareGoodsList = JSON.parseArray(data, ShareGoodsVO.class);
            // 购买用户
            UserInfoDetailVO userInfo = userInfoMapper.getUserInfoDetail(shareGoodsList.get(0).getBuyUserId().toString());
            // 分享人
            List<String> shareUserIdList = shareGoodsList.stream().map(ShareGoodsVO::getShareUserId).distinct().collect(Collectors.toList());
            // 1.查询所有已存在第一次分享购买记录的用户数据
            List<UserInviteRecordVO> inviteRecordList = userInviteRecordMapper.queryVKByShareUser(shareUserIdList,shareGoodsList.get(0).getBuyUserId(), CommonType.inviteRecordType.SHARE_GOODS.getCode());
            List<String> invitedUserList = inviteRecordList.stream().map(UserInviteRecordVO::getUserId).distinct().collect(Collectors.toList());
            shareUserIdList.removeAll(invitedUserList);

            // 2.增加所有第一次邀请购买记录
            List<UserInviteRecordVO> userInviteRecordList = new ArrayList<>();
            for (String shareUserId : shareUserIdList) {
                UserInviteRecordVO userInviteRecord = new UserInviteRecordVO(userInfo,shareUserId);
                userInviteRecord.setInviteType(CommonType.inviteRecordType.SHARE_GOODS.getCode());
                userInviteRecordList.add(userInviteRecord);
            }
            // 查询购买用户 是否是 微客
            Integer shareUserId = this.baseMapper.queryVkStart(userInfo.getUserId());
            int result = userInviteRecordMapper.insertBatch(userInviteRecordList);
            if (result > 0) {
                for(ShareGoodsVO shareGoods : shareGoodsList){
                    // 首次分享才记录分享次数
                    /**
                     * 分享按次数 分享一次加一  推广按人数 首次绑定加一
                     */
                    if(null != inviteRecordList && inviteRecordList.size() > 0){
                        shareGoods.setInviteNum(0);
                        shareGoods.setTgCommission(new BigDecimal(0));
                        //将推广佣金更新 回订单佣金记录表
                        this.baseMapper.updateOrderTGCommission(shareGoods.getOrderId(),new BigDecimal(0),"0");

                    }else{
                        //如果是空 证明不是微客 首次购买绑定
                        if(null == shareUserId){
                            shareGoods.setInviteNum(1);
                        }else{
                            shareGoods.setInviteNum(0);
                        }
                    }
                    //2 是当前用户已经是微客 主动在商城购买分销商品 他的上级获得推广佣金 但不加推广 和 分享次数
                    if(2 == shareGoodsList.get(0).getFxTg()){
                        shareGoods.setShareNum(0);
                    }else{
                        shareGoods.setShareNum(1);
                    }

                    // 3 当此笔单是通过分享进了的 分享人的分享用户 购物人上级同时的推广佣金
                    //判断平台是否开启推广佣金
                    GoodsVkSetVO goodsVkSet = this.baseMapper.queryGoodsVkSet();
                    if(null != goodsVkSet && goodsVkSet.getCommisionConfig() != 2 && null != shareUserId){
                        //判断分享人和购买人是否是 绑定关系 分享人userId 和 购买人上级id 是否相等
                        if(!shareGoods.getShareUserId().equals(shareUserId)){
                            //查询商品的推广佣金比例
                            String tgRate = this.baseMapper.queryGoodsTgRate(shareGoods.getGoodsId());
                            if(null == tgRate){
                                tgRate = "0";
                            }
                            //计算推广佣金
                            double tg = Double.parseDouble(tgRate)/100;
                            BigDecimal  tgCommission = shareGoods.getOrderPrice().multiply(new BigDecimal(tg).setScale(2, BigDecimal.ROUND_HALF_UP));
                            // 不相等 则 分享人 不是购买人的上级 ，购买人真正的上级用户 得推广佣金
                            this.baseMapper.updateVkTgCommission(shareUserId,tgCommission);
                            //将推广佣金更新 回订单佣金记录表
                            this.baseMapper.updateOrderTGCommission(shareGoods.getOrderId(),tgCommission,tgRate);
                        }
                    }
                    // 更新微客用户分享次数  和 推广 人数 和微客佣金
                    this.baseMapper.updateVkCommission(shareGoods);
                }
            }
            // 员工用户更新订单额
            userYgInfoMapper.updateUserShareOrder(shareGoodsList);
            // 判断当前用户是否是购买店铺会员  不是则增加会员记录
            return this.addShopVipUser(shareGoodsList,userInfo, CommonType.vipUserSource.BUY_GOODS.getCode());

        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.fail(0, "操作异常");
        }
    }
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult addShopVipUser(List<ShareGoodsVO> shareGoodsList, UserInfoDetailVO userInfo,Integer  vipSource){
        try {
            List<Integer> shopIdList = shareGoodsList.stream().map(ShareGoodsVO::getShopId).distinct().collect(Collectors.toList());
            List<ShopVipUserVO> shopVipUserList = userVipMapper.queryVipUserBatch(userInfo.getUserId(), shopIdList);
            List<Integer> vipShopIdList = shopVipUserList.stream().map(ShopVipUserVO::getShopId).distinct().collect(Collectors.toList());
            shopIdList.removeAll(vipShopIdList);
            // 非店铺会员增加会员记录
            shareGoodsList = shareGoodsList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(t->t.getShopId()))),ArrayList::new));
            Map<Integer, ShareGoodsVO> map = shareGoodsList.stream().collect(Collectors.toMap(ShareGoodsVO::getShopId, Function.identity()));
            List<ShopVipUserVO> shopVipUsers = new ArrayList<>();
            for (Integer shopId : shopIdList) {
                ShopVipUserVO shopVipUser = new ShopVipUserVO(userInfo);
                shopVipUser.setShopId(shopId);
                shopVipUser.setShopUserId(map.get(shopId).getShareUserId());
                shopVipUser.setVar1(vipSource);
                shopVipUser.setVar2(map.get(shopId).getShareUserId());
                shopVipUsers.add(shopVipUser);
            }
            if(!CollectionUtils.isEmpty(shopVipUsers)) {
                // userVipMapper.insertBatch(shopVipUsers);
            }
            return ResponseResult.success("操作成功");
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.fail(0, "操作异常");
        }
    }

    @Override
    public ResponseResult addShopVipUser(String data) {
        List<ShareGoodsVO> shareGoodsList = JSON.parseArray(data, ShareGoodsVO.class);
        // 购买用户
        UserInfoDetailVO userInfo = userInfoMapper.getUserInfoDetail(shareGoodsList.get(0).getBuyUserId().toString());
        return this.addShopVipUser(shareGoodsList,userInfo,CommonType.vipUserSource.SELF_BUY_GOODS.getCode());
    }

    @Override
    public ResponseResult vkApply(Map<String,List<VkApplyOrderVO>> data) {
        try {
            List<VkApplyOrderVO> vkApplyOrderList = data.get("vkApplyOrderList");
            // 1.申请微客的用户
            UserInfoDetailVO userInfo = userInfoMapper.getUserInfoDetail(vkApplyOrderList.get(0).getBuyerUserId());
            // 2..查询微客申请条件
            VKSetVO vkSet = queryVkSet();
            for (VkApplyOrderVO vkApplyOrder : vkApplyOrderList) {
                /*
                  分享给用户申请微客的  商家或微客用户信息[shopId有值的则是商家  否则是微客]
                 */
                UserInfoDetailVO parentUserInfo = userInfoMapper.getShreUserInfoDetail(vkApplyOrder.getShareUserId());
                // parentUserInfo.setUserBindShopId(vkApplyOrder.getShopId());
                // 如果分享用户无门店信息  有可能 当前用户是门店员工申请的微客 保存当前用户门店信息
                if(null == parentUserInfo.getUserBindStoreId()) {
                    parentUserInfo.setUserBindStoreId(userInfo.getUserBindStoreId());
                    parentUserInfo.setUserBindStoreName(userInfo.getUserBindStoreName());
                }

                String shopName = this.baseMapper.queryShopName(parentUserInfo.getUserBindShopId());
                // 当前用户添加到店铺会员
                ShopVipUserVO shopVipUser = userVipMapper.queryVipUser(vkApplyOrder.getBuyerUserId(), parentUserInfo.getUserBindShopId());
                if (null == shopVipUser) {
                    ShopVipUserVO shopAddVipUser = new ShopVipUserVO(userInfo);
                    shopAddVipUser.setShopId(parentUserInfo.getUserBindShopId());
                    shopAddVipUser.setShopName(shopName);
                    shopAddVipUser.setStoreId(parentUserInfo.getUserBindStoreId());
                    shopAddVipUser.setStoreName(parentUserInfo.getUserBindStoreName());
                    shopAddVipUser.setShopUserId(parentUserInfo.getUserId());
                    shopAddVipUser.setVar1(CommonType.vipUserSource.VK_APPLY_BUY.getCode());
                    // 当前用户成为邀请关联店铺会员
                    userVipMapper.addVipUser(shopAddVipUser);
                }
                // 微客推广开启 成为微客满足指定条件 且 包括购买商品
                if (null != vkSet && vkSet.getVkState() == 1 && vkSet.getConditionType().intValue() != CommonType.vKAddCondition.INVITE_USER.getCode()) {
                    boolean flag = true;
                    ShopVkApplyVO shopVkApply = this.baseMapper.queryShopVkApply(userInfo.getUserId(), parentUserInfo.getUserBindShopId());
                    if (null == shopVkApply) {
                        shopVkApply = new ShopVkApplyVO(vkApplyOrder.getBuyerUserId(), parentUserInfo.getUserBindShopId(), vkApplyOrder.getBuyNum(), 0, 1);
                    } else {
                        // 用户已经是微客直接返回
                        if (shopVkApply.getApplyStatus() == 2 || shopVkApply.getApplyStatus() == 3) {
                            flag = false;
                        }
                        shopVkApply.setBuyGoodsNum(shopVkApply.getBuyGoodsNum() + vkApplyOrder.getBuyNum());
                    }
                    if(flag){
                        // 用户申请微客成功返回
                        ShopVkApplyVO vkApply = this.addVKApply(userInfo, parentUserInfo, shopName, shopVkApply, vkSet);
                        if (null != vkApply) {
                            if (null == vkApply.getId()) {
                                this.baseMapper.insertVkApplySelective(vkApply);
                            } else {
                                this.baseMapper.updateApplyBuyNum(vkApplyOrder.getBuyNum(), vkApply.getApplyStatus(), vkApply.getId());
                            }
                            // 更新微客用户绑定店铺信息
                            userInfoMapper.updateUserBindShop(parentUserInfo.getUserBindShopId(), parentUserInfo.getUserBindStoreId(), userInfo.getUserId());
                        }
                    }
                }
            }
        }catch (Exception e){
            System.err.println(e.getMessage());
            return ResponseResult.fail(0, "异常");
        }
        return ResponseResult.success("成功");
    }

    @Override
    public ResponseResult vkApplyPage(Map<String, String> vkApplyConfirm) {

        // 获取用户信息
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(vkApplyConfirm.get("token"));

        // 获取微客配置信息
        VKSetVO vkSet = this.queryVkSet();
        // 微客开启
        if (null != vkSet && vkSet.getVkState() == 1) {
            // 如果没有上级邀请人信息
            if (null == vkApplyConfirm.get("shareUserId")) {
                VKApplyPageVO vkApplyPage = new VKApplyPageVO(vkSet);
                vkApplyPage.setReceiveNum(0);
                return ResponseResult.success(vkApplyPage);
            }

            // 获取分享用户信息
            UserInfoDetailVO shareUserInfo = userInfoMapper.getUserInfoDetail2(vkApplyConfirm.get("shareUserId"));

            VKApplyPageVO vkApplyPage = new VKApplyPageVO(vkSet);

            // 1、校验用户是否已经是微客
            UserVkEntity vkUserInfo = this.baseMapper.selectOne(new LambdaUpdateWrapper<UserVkEntity>()
                    .eq(UserVkEntity::getUserId,userInfo.getUserId())
                    .in(UserVkEntity::getUserStatus,1,3));
            if (null != vkUserInfo) {
                return ResponseResult.fail(0, "您是微客无需申请",vkApplyPage);
            }

            // 如果微客添加不是只有购买商品 查询用户已邀请人数
            if (vkSet.getConditionType().intValue() !=CommonType. VKSetType.BUY_GOODS.getCode()) {
                UserVkApplyEntity shopVkApply = userVkApplyMapper.selectOne(new LambdaQueryWrapper<UserVkApplyEntity>()
                                                .eq(UserVkApplyEntity::getUserId,userInfo.getUserId())
                                                .eq(UserVkApplyEntity::getShopId,shareUserInfo.getUserBindShopId()));
                vkApplyPage.setReceiveNum(null == shopVkApply ? 0 : shopVkApply.getInviteUserNum());
            }

            // 2、校验用户是否是员工  且当前邀请人不是员工的商家邀请人
            UserYgInfoEntity shopYgUserInfo = userYgInfoMapper.selectOne(new LambdaUpdateWrapper<UserYgInfoEntity>()
                                                .eq(UserYgInfoEntity::getUserId,userInfo.getUserId())
                                                .in(UserYgInfoEntity::getUserStatus,1,3));
            if (null != shopYgUserInfo && !shopYgUserInfo.getShopUserId().equals(shareUserInfo.getUserId())) {
                return ResponseResult.fail(0, "您是员工用户请联系商家申请",vkApplyPage);
            }
            return ResponseResult.success(vkApplyPage);
        } else {
            // 微客关闭
            VKApplyPageVO vkApplyPage = new VKApplyPageVO(vkSet);
            return ResponseResult.fail(0, "微客推广已关闭",vkApplyPage);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult vkApplyConfirm(Map<String, String> vkApplyConfirm) {
        try {
            if(null == vkApplyConfirm.get("shareUserId")){
                return ResponseResult.fail(BizCodeEnume.APPLY_ERROR);
            }
            // 获取用户信息
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(vkApplyConfirm.get("token").toString());
            // 获取分享用户信息
            UserInfoDetailVO shareUserInfo = userInfoMapper.getUserInfoDetail2(vkApplyConfirm.get("shareUserId").toString());

            // 获取微客配置信息
            VKSetVO vkSet = this.queryVkSet();

            // 微客开启
            if (null != vkSet && vkSet.getVkState().intValue() == 1) {
                // 1、校验用户是否已经是微客
                UserVkEntity vkUserInfo = this.baseMapper.selectOne(new LambdaUpdateWrapper<UserVkEntity>()
                                        .eq(UserVkEntity::getUserId,userInfo.getUserId())
                                        .in(UserVkEntity::getUserStatus,1,3));
                if (null != vkUserInfo) {
                    return ResponseResult.fail(BizCodeEnume.VK_USER);
                }

                // 2、校验用户是否是员工  且当前邀请人不是员工的商家邀请人
                UserYgInfoEntity shopYgUserInfo = userYgInfoMapper.selectOne(new LambdaUpdateWrapper<UserYgInfoEntity>()
                                                    .eq(UserYgInfoEntity::getUserId,userInfo.getUserId())
                                                    .in(UserYgInfoEntity::getUserStatus,1,3));
                if (null != shopYgUserInfo) {
                    if (!shopYgUserInfo.getShopUserId().equals(shareUserInfo.getUserId())) {
                        return ResponseResult.fail(BizCodeEnume.OTHER_YG_USER);
                    } else {
                        // 员工用户保存自己的门店信息
                        shareUserInfo.setUserBindStoreId(shareUserInfo.getUserBindStoreId());
                        shareUserInfo.setUserBindStoreName(shareUserInfo.getUserBindStoreName());
                    }
                }

                // 3.判断用户是否已经满足所有申请条件
                UserVkApplyEntity shopVkApply = userVkApplyMapper.selectOne(new LambdaQueryWrapper<UserVkApplyEntity>()
                                                .eq(UserVkApplyEntity::getUserId,userInfo.getUserId())
                                                .eq(UserVkApplyEntity::getShopId,shareUserInfo.getUserBindShopId()));
                if (null == shopVkApply || shopVkApply.getApplyStatus() != 2) {
                    return  ResponseResult.fail(BizCodeEnume.CONDITION_NOT_MET);
                }

                // 4.校验成功后 申请用户微客记录  更新申请记录状态
                userVkApplyMapper.update(null,new LambdaUpdateWrapper<UserVkApplyEntity>()
                                 .set(UserVkApplyEntity::getApplyStatus,2)
                                 .eq(UserVkApplyEntity::getId,shopVkApply.getId()));
                // 生成微客记录
                String shopName = this.baseMapper.queryShopName(shareUserInfo.getUserBindShopId());
                UserVkEntity shopVKUser=new UserVkEntity();
                shopVKUser.setUserId(userInfo.getUserId());
                shopVKUser.setUserName(userInfo.getUserName());
                shopVKUser.setMobile(userInfo.getUserMobile());
                shopVKUser.setShopId(shareUserInfo.getShopId());
                shopVKUser.setShopName(shopName);
                shopVKUser.setStoreId(shareUserInfo.getUserBindStoreId());
                shopVKUser.setStoreName(shareUserInfo.getUserBindStoreName());
                shopVKUser.setShopUserId( shareUserInfo.getUserId().toString());
                shopVKUser.setUserStatus(CommonType.vKStatus.PASS.getCode());
                shopVKUser.setCreateTime(DateUtils.getNowDateToString());
                // 商家邀请微客
                if (null != shareUserInfo.getShopId() && shareUserInfo.getShopId() > 0) {
                    shopVKUser.setVar1(CommonType.vKAddType.MALL_INVITE.getCode().toString());
                } else {
                    // 微客邀请
                    shopVKUser.setVar1(CommonType.vKAddType.VK_INVITE.getCode().toString());
                }
                shopVKUser.setUserStatus(CommonType.vKStatus.AUTH.getCode());
                this.baseMapper.insert(shopVKUser);

                //更新微客邀请人的推广人数
                this.baseMapper.updateVkTgNum(shareUserInfo.getUserId());
                return ResponseResult.success();
            } else {
                // 微客关闭
                return ResponseResult.fail(BizCodeEnume.VK_CLOSE);
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return  ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
        }
    }

    /**
     * 查询微客推广配置
     * @return
     */
    public VKSetVO queryVkSet(){
        return userVkSetMapper.selectByPrimaryKey(VKSetVO.VK_SET_ID);
    }
    @Transactional(rollbackFor = Exception.class)
    public ShopVkApplyVO addVKApply(UserInfoDetailVO userInfo,UserInfoDetailVO parentUserInfo,String shopName, ShopVkApplyVO shopVkApply,VKSetVO vkSet) {
        try {
            if (null == parentUserInfo || null == parentUserInfo.getUserBindShopId()) {
                return null;
            }
            // 满足条件验证
            Boolean flag = this.vkApplyCheck(vkSet, shopVkApply);
            if (flag) {
                // 满足条件 如果微客申请是自动成为  则用户成为微客
                if (vkSet.getApplyType() == 1) {
                    shopVkApply.setApplyStatus(3);
                    // 生成微客用户记录
                    ShopVKUserVO shopVKUserVO = new ShopVKUserVO(userInfo, parentUserInfo, shopName);
                    // 商家邀请微客
                    if (null != parentUserInfo.getShopId() && parentUserInfo.getShopId() > 0) {
                        shopVKUserVO.setVar1(CommonType.vKAddType.MALL_INVITE.getCode());
                    } else {
                        // 微客邀请
                        shopVKUserVO.setVar1(CommonType.vKAddType.VK_INVITE.getCode());
                    }
                    this.baseMapper.insertSelective(shopVKUserVO);
                    //更新微客邀请人的推广人数
                    this.baseMapper.updateVkTgNum(parentUserInfo.getUserId());
                } else {
                    // 如果微客申请是客户申请 则等待用户申请 更新申请记录表状态为可申请
                    shopVkApply.setApplyStatus(2);
                }
                return shopVkApply;
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return null;
    }
    /**
     * 微客申请校验
     * @param vkSet
     * @param shopVkApply
     * @return
     */
    private Boolean vkApplyCheck(VKSetVO vkSet, ShopVkApplyVO shopVkApply){
        Boolean flag = false;
        if(vkSet.getApplyCondition().intValue() == CommonType.vKAddCondition.RANDOM.getCode()){
            // 1.满足任一条件 且不是唯一的邀请会员 则用户可成为微客
            if(vkSet.getConditionType().intValue() != CommonType.vKAddCondition.INVITE_USER.getCode()){
                flag = true;
            }
        }else{
            if(vkSet.getConditionType().intValue() == CommonType.vKAddCondition.BUY_GOODS.getCode()){
                // 如果条件是购买则用户可成为微客
                flag = true;
            } else if(vkSet.getConditionType().intValue() == CommonType.vKAddCondition.BUY_INVITE.getCode()){
                // 如果条件是购买+邀请  判断是否已经购买商品
                if(shopVkApply.getInviteUserNum().intValue()>=vkSet.getInviteNum().intValue()){
                    flag = true;
                }
            }
        }
        return flag;
    }

    @Override
    public ResponseResult addVkInfo(Map<String, Object> map) {
        // 获取用户信息
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());
        String userId = map.get("userId").toString();
        //校验手机号是否注册
        Map<String,Object>  regStart = this.baseMapper.queryUserReg(userId);
        if(null == regStart){
            return ResponseResult.fail(BizCodeEnume.MOBILE_NUMBER_NOT_EXIST);
        }
        //校验当前用户是否已经成为微客
        Integer vipStart = userVipMapper.queryUserVipStart(regStart);
        Integer vkStart = this.baseMapper.queryUserVkStart(regStart);
        if(0 != vipStart && 0 != vkStart){
            return ResponseResult.fail(BizCodeEnume.USER_IS_VK);
        }
        regStart.put("sex",1);
        regStart.put("shopId",userInfo.getShopId());
        String shopName = this.baseMapper.queryShopName(Integer.valueOf(userInfo.getShopId()));
        regStart.put("shopName",shopName);
        regStart.put("shopUserId",userInfo.getUserId());
        regStart.put("var1",1);
        if(vipStart == 0){
            userVipMapper.addVkVip(regStart);
        }
        if(vkStart == 0) {
            this.baseMapper.addVkUser(regStart);
        }
        UserVkApplyEntity vkApply = userVkApplyMapper.selectOne(new LambdaQueryWrapper<UserVkApplyEntity>()
                .eq(UserVkApplyEntity::getShopId,regStart.get("shopId"))
                .eq(UserVkApplyEntity::getUserId,regStart.get("userId")));
        if(vkApply == null) {
            userVkApplyMapper.addVkUserApply(regStart);
        }else {
            userVkApplyMapper.update(null, new LambdaUpdateWrapper<UserVkApplyEntity>()
                    .set(UserVkApplyEntity::getBuyGoodsNum,1)
                    .set(UserVkApplyEntity::getInviteUserNum,0)
                    .set(UserVkApplyEntity::getApplyStatus,3)
                    .eq(UserVkApplyEntity::getShopId,regStart.get("shopId"))
                    .eq(UserVkApplyEntity::getUserId,regStart.get("userId")));
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryShopVk(MallVkQueryVO mallVkQuery) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(mallVkQuery.getToken());
        mallVkQuery.setShopId(userInfo.getShopId());
        try {
            Map data = ParseMapUtils.beanToMap(mallVkQuery);
            IPage<MallVkCommissionVO> page =  this.baseMapper.queryVKUserList(new Query<MallVkCommissionVO>().getPage(data),mallVkQuery);
            List<MallVkCommissionVO> vkCommissionList = page.getRecords();
            for (MallVkCommissionVO vkCommission :vkCommissionList){
                VKUserVO vkUser1 = this.baseMapper.queryShopVkUser1(vkCommission.getUserId());
                if (vkUser1==null){
                    vkCommission.setFxCommission("0");
                    vkCommission.setTgCommission("0");
                    vkCommission.setAllCommission("0");
                }else {
                    vkCommission.setFxCommission(vkUser1.getCommissionSharing());
                    vkCommission.setTgCommission(vkUser1.getPromotionCommission());
                    vkCommission.setAllCommission(vkUser1.getTotalCommission());
                }
                Integer integer = this.baseMapper.queryVKUserList1(vkCommission.getUserId());
                vkCommission.setShareNum(integer);
            }
            page.setRecords(vkCommissionList);
            return ResponseResult.success(PageUtils.getPage(page));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return ResponseResult.fail();
    }

    @Override
    public ResponseResult ygApplyPage(UserApplyConfirmDTO ygApplyConfirm) {
        if(StringUtils.isBlank(ygApplyConfirm.getToken())){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_NULL);
        }
        // 获取用户信息
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(ygApplyConfirm.getToken());
        if(null == userInfo){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        // 获取微客配置信息
        VKSetVO vkSet = this.queryVkSet();
        // 微客开启
        if (null != vkSet && vkSet.getVkState() == 1) {
            if (null == ygApplyConfirm.getShareUserId()) {
                if (null == userInfo.getShopId()) {
                    return ResponseResult.fail(BizCodeEnume.NOT_BUSINISS);
                }
                // 查询店铺所有门店信息
                List<ShopStoreInfoVO> shopStoreInfoList = this.baseMapper.queryByShop(Integer.parseInt(userInfo.getShopId()));

                if (CollectionUtils.isEmpty(shopStoreInfoList)) {
                    return ResponseResult.fail(BizCodeEnume.NO_STORE);
                }
                Map<String, Object> map = new HashMap<>(8);
                map.put("image", vkSet.getVkImage());
                map.put("shopStoreInfoList", shopStoreInfoList);
                return ResponseResult.success(map);
            }

            // 获取分享用户信息
            UserInfoDetailVO shareUserInfo = userInfoMapper.getUserInfoDetail(ygApplyConfirm.getShareUserId().toString());

            // 1、校验用户是否已经员工
            ShopYgUserInfoDTO shopYgUserInfo = userYgInfoMapper.queryYgByUserId(userInfo.getUserId());
            if (null != shopYgUserInfo) {
                return ResponseResult.fail(BizCodeEnume.YG_USER);
            }
            // 2.判断用户是否是其他商家微客
            ShopVKUserVO vkUserInfo = this.baseMapper.queryVKUserDetail(userInfo.getUserId());
            if (null != vkUserInfo && vkUserInfo.getShopId().intValue() != shareUserInfo.getUserBindShopId()) {
                return ResponseResult.fail(BizCodeEnume.OTHER_VK_USER);
            }

            // 3.查询店铺所有门店信息
            List<ShopStoreInfoVO> shopStoreInfoList = this.baseMapper.queryByShop(shareUserInfo.getUserBindShopId());

            if (CollectionUtils.isEmpty(shopStoreInfoList)) {
                return ResponseResult.fail(BizCodeEnume.NO_STORE);
            }

            Map<String, Object> map = new HashMap<>(8);
            map.put("image", vkSet.getVkImage());
            map.put("shopStoreInfoList", shopStoreInfoList);
            return ResponseResult.success(map);
        } else {
            // 微客关闭
            return ResponseResult.fail(BizCodeEnume.VK_CLOSE);
        }
    }

    @Override
    public ResponseResult getAskUserInfo(Map<String, String> paraMap) {
        String token = paraMap.get("token");
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        //查询出我的微客信息，拿到我的邀请人ID
        VKUserInfoVO vkUserInfo = this.baseMapper.queryVkUser(userInfo.getUserId());
        return ResponseResult.success(vkUserInfo);
    }

    @Override
    public ResponseResult queryYgRank(YgRankVO ygRank) {
        Map<String, Object> map = new HashMap<>(8);
        Page<YgRankVO> page;
        if(ygRank.getPage() == null && ygRank.getLimit() == null){
            page = new Page<>(0,-1);
        }else{
            page = new Page<>(ygRank.getPage(),ygRank.getLimit());
        }
        // 1.用户未登录
        if (StringUtils.isBlank(ygRank.getToken())) {
            IPage<YgRankVO> ygRankList = this.baseMapper.queryUserRankList(page,ygRank);
            map.put("userRank",null);
            map.put("ygRankList",PageUtils.getPage(ygRankList));
            return ResponseResult.success(map);
        } else {
            // 2.用户已登录
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(ygRank.getToken());
            // 1.查询所有排行
            IPage<YgRankVO> ygRankList = this.baseMapper.queryUserRankList(page,ygRank);
            // 2.查询登录用户排行
            ygRank.setUserId(userInfo.getUserId());
            IPage<YgRankVO> userRank = this.baseMapper.queryUserRankList(page,ygRank);
            // 3.所有排行列表中删除登录用户数据
            if(CollectionUtils.isEmpty(userRank.getRecords())){
                map.put("userRank",null);
            }else{
                map.put("userRank",userRank.getRecords().get(0));
                ygRankList.getRecords().removeAll(userRank.getRecords());
            }
            map.put("ygRankList",PageUtils.getPage(ygRankList));
            return ResponseResult.success(map);
        }
    }

    @Override
    public ResponseResult queryTodayShareGoods(FXGoodsListVO goodsListRequest) {
        if (null != goodsListRequest.getCatId()) {
            ResponseResult resultResp = goodsServiceClient.queryFxCatList(goodsListRequest.getCatId());
            List<Integer> catIds = JSON.parseArray(resultResp.getData().toString(), Integer.class);
            if (!CollectionUtils.isEmpty(catIds)) {
                goodsListRequest.setCatIds(catIds);
                goodsListRequest.setCatId(0);
            }
        }

        Page<TodayShareGoodsVO> page = new Page<>(goodsListRequest.getPage(), goodsListRequest.getLimit());
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(goodsListRequest.getToken());

        goodsListRequest.setUserId(userInfo.getUserId());
        IPage<TodayShareGoodsVO> orderCommissionList = this.baseMapper.queryTodayShareGoods(page,goodsListRequest);

        return ResponseResult.success(PageUtils.getPage(orderCommissionList));
    }
}
